<?php
/**
 * NfxCommissionCalculate.php
 *
 * Niushop商城系统 - 团队十年电商经验汇集巨献!
 * =========================================================
 * Copy right 2015-2025 山西牛酷信息科技有限公司, 保留所有权利。
 * ----------------------------------------------
 * 官方网址: http://www.niushop.com.cn
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用。
 * 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
 * =========================================================
 * @author : niuteam
 * @date : 2015.1.17
 * @version : v1.0.0.0
 */

namespace addons\Nsfx\data\service;

use addons\Nsfx\data\model\NfxCommissionDistributionModel;
use addons\Nsfx\data\model\NfxCommissionPartnerModel;
use addons\Nsfx\data\model\NfxCommissionRegionAgentModel;
use addons\Nsfx\data\model\NfxGoodsCommissionRateModel;
use addons\Nsfx\data\model\NfxPartnerLevelModel;
use addons\Nsfx\data\model\NfxPromoterLevelModel;
use addons\Nsfx\data\model\NfxPromoterModel;
use addons\Nsfx\data\model\NfxPromoterRegionAgentModel;
use addons\Nsfx\data\model\NfxPromoterRegionAgentApplyModel;
use addons\Nsfx\data\model\NfxShopConfigModel;
use addons\Nsfx\data\model\NfxShopMemberAssociationModel;
use addons\Nsfx\data\model\NfxShopRegionAgentConfigModel;
use addons\Nsfx\data\model\NfxPromoterGoodsModel;
use data\model\NsGoodsModel;
use data\model\NsOrderGoodsModel;
use data\model\NsOrderGoodsPromotionDetailsModel;
use data\model\NsOrderModel;
use data\service\BaseService;
use data\service\Config;

/**
 *佣金计算
 */
class NfxCommissionCalculate extends BaseService
{
	private $order_info = null;    //订单信息
	private $buyer_uid = 0;     //购买人
	private $promoter_id = 0;   //购买人分销商
    private $promoter_uid = 0;   //购买人uid
    private $parent_promoter = 0;    //分销上级
    private $parent_promoter_uid = 0;   //分销上级uid
    private $parent_promoter_is_agent = 0; //父级是否是服务中心
    private $parent_promoter_agent_category = []; //父级服务中心所有品类
	private $partner_id;    //购买人股东
	private $is_distribution_enable; // 是否开启三级分销
	private $is_distribution_audit; // 分销商是否需要审核
	private $is_regional_agent; // 是否开启区域分销
	private $is_partner_enable; // 股东分红是否开启
	private $is_global_enable; // 全球分红是否开启
	private $is_distribution_start; // 分销是否申请
    private $reward_set;
	
	/**
	 * 构造函数
	 * @param number $order_id
	 */
	public function __construct($order_id = 0, $order_goods_ids = null)
	{
        $this->getRewardSet();
		$this->order_info = $this->getOrderInfo($order_id, $order_goods_ids);
        $this->getPromoter();
	}

    /**
     * 获取订单金额相关信息
     * @param unknown $order_id
     */
    private function getOrderInfo($order_id, $order_goods_ids)
    {
        if ($order_id != 0) {
            //订单基础信息
            $order_model = new NsOrderModel();
            $order_info = $order_model->get($order_id);
            //订单项信息
            $order_goods_model = new NsOrderGoodsModel();
            $condition["order_id"] = $order_id;
            if (!empty($order_goods_ids)) {
                $condition["order_goods_id"] = array( "in", $order_goods_ids );
            }
            $order_goods_list = $order_goods_model->getQuery($condition);
            foreach ($order_goods_list as $k => $order_goods) {
                $order_goods_promotion = new NsOrderGoodsPromotionDetailsModel();
                $promotion_money = $order_goods_promotion->where([ 'order_id' => $order_id, 'sku_id' => $order_goods['sku_id'] ])->sum('discount_money');
                if (empty($promotion_money)) {
                    $promotion_money = 0;
                }

                $order_goods_list[ $k ]['promotion_money'] = $promotion_money;
                $order_goods_list[ $k ]['cost_price'] = $order_goods['cost_price'] * $order_goods['num'];
                $order_goods_list[ $k ]['real_pay'] = $order_goods['goods_money'] + $order_goods['adjust_money'] - $order_goods['refund_real_money'] - $promotion_money - $order_goods['refund_balance_money'];

                //佣金计算基准
                $goods_return_money = $order_goods['goods_money'] - $order_goods['refund_real_money'] - $promotion_money - $order_goods['refund_balance_money'];
                if ($goods_return_money < 0) {
                    $goods_return_money = 0;
                }
                $order_goods_list[ $k ]['goods_return'] = $goods_return_money;

                //计算佣金分配信息
                $reward_set = $this->reward_set;
                $order_goods_list[ $k ]['commission_rate_promoter'] = $reward_set['value']['promoter_reward_rate'];//推广员部分
                $order_goods_list[ $k ]['commission_rate_agent'] = $reward_set['value']['agent_reward_rate'];//区域代理部分
            }
            $order_info['order_goods_list'] = $order_goods_list;
            return $order_info;
        } else {
            return '';
        }
    }

    /**
     * 获取购买人，分销商，股东
     */
    private function getPromoter()
    {
        if (!empty($this->order_info)) {
            $this->buyer_uid = $this->order_info['buyer_id'];
            $this->promoter_uid = $this->order_info['buyer_id'];
            $promoter_model = new NfxPromoterModel();
            $promoter_info = $promoter_model->getInfo(['shop_id' => $this->instance_id, 'uid' => $this->buyer_uid], "promoter_id,parent_promoter");
            $this->promoter_id = $promoter_info['promoter_id'];
            $this->parent_promoter = $promoter_info['parent_promoter'];
            $this->parent_promoter_uid = 0;
            if($this->parent_promoter){
                $parent_promoter_info = $promoter_model->getInfo(['shop_id' => $this->instance_id, 'promoter_id' => $this->parent_promoter], "uid, is_region_agent");
                $this->parent_promoter_uid = $parent_promoter_info['uid'];
                $this->parent_promoter_is_agent = $parent_promoter_info['is_region_agent'];
            }
        }
    }

    /**
     * 奖励设置
     */
	private function getRewardSet()
    {
        $config_service = new Config();
        $reward_set = $config_service->getRewardConfig();
        $this->reward_set = $reward_set;
    }

    /**
     * 分销订单佣金
     *
     */
    public function orderdistributionCommission()
    {

            $commossion_distribution = new NfxCommissionDistributionModel();
            $promoter_goods_model = new NfxPromoterGoodsModel();

            if (empty($this->order_info)) {
                return 1;
            }
            $order_goods_model = new NsOrderGoodsModel();
            $commossion_distribution->startTrans();
            try {
                $res = [];
                //本次订单购买的商品id的记录
                $goods_id_arr = [];
                foreach ($this->order_info['order_goods_list'] as $k => $order_goods) {
                    if (empty($order_goods['commission_rate_promoter'])) {
                        continue;
                    }

                    //查看自己在之前的订单中有没有买过该商品 有则跳过
                    $order_goods_count = $order_goods_model
                        ->alias('og')
                        ->join([
                            ['ns_order o', 'og.order_id = o.order_id', 'left'],
                        ])
                        ->where([
                            'o.buyer_id' => $this->order_info['buyer_id'],
                            'o.order_id' => ['neq', $this->order_info['order_id']],
                            'o.order_status' => ['in', '1,2,3,4'],
                            'og.goods_id' => $order_goods['goods_id'],
                        ])
                        ->count();
                    if($order_goods_count > 0) continue;

                    //如果本次订单中已经购买了同种商品则不再进入
                    if(in_array($order_goods['goods_id'], $goods_id_arr)) continue;

                    //查看邀请人和分享人有没有购买过该产品
                    $invite_uid = $this->parent_promoter_uid;
                    $share_uid = $order_goods['share_uid'];
                    $invite_goods_info = $promoter_goods_model->getInfo(['uid' => $invite_uid, 'goods_id' => $order_goods['goods_id'], 'confirm_status' => 1]);
                    $share_goods_info = $promoter_goods_model->getInfo(['uid' => $share_uid, 'goods_id' => $order_goods['goods_id'], 'confirm_status' => 1]);
                    if(!empty($share_goods_info)){
                        //分享人有购买过，优先分享人
                        $reward_promoter = $share_goods_info['promoter_id'];
                    }else if(!empty($invite_goods_info)){
                        //分享人没有购买过，邀请人购买过，则是邀请人
                        $reward_promoter = $invite_goods_info['promoter_id'];
                    }else{
                        //如果都没有则跳过
                        $reward_promoter = 0;
                    }
                    if($reward_promoter == 0) continue;

                    //获取佣金信息
                    $res_item = [];
                    $commission_rate = $order_goods['commission_rate_promoter'];
                    if (!empty($commission_rate)) {
                        //记录本次订单购买的商品id数据
                        $goods_id_arr[$order_goods['goods_id']] = $order_goods['goods_id'];
                        $res_item['add_promoter_commission_res'] = $this->addOrderDistributionCommission(
                            $this->instance_id,
                            $reward_promoter,
                            $this->order_info['order_id'],
                            $order_goods['order_goods_id'],
                            //分享奖励只发放一件商品的部分
                            $order_goods['real_pay'] / $order_goods['num'],
                            $order_goods['cost_price'] / $order_goods['num'],
                            $order_goods['goods_return'] / $order_goods['num'],
                            0,
                            $commission_rate
                        );
                    }
                    $res[] = $res_item;
                }
                $commossion_distribution->commit();
                return $res;
            } catch (\Exception $e) {
                $commossion_distribution->rollback();
                dump($e->getMessage());
                return $e->getMessage();
            }

    }
	
	/**
	 * 订单退款后 更新三级分销的佣金
	 */
	public function updateOrderDistributionCommission()
	{
		$commossion_distribution = new NfxCommissionDistributionModel();
		if (empty($this->order_info)) {
			return 1;
		}
		$commossion_distribution->startTrans();
		try {
			foreach ($this->order_info['order_goods_list'] as $k => $order_goods) {
				#订单项id
				$order_goods_id = $order_goods["order_goods_id"];
				#查询当前订单项产生的三级分销佣金流水
				$commission_list = $commossion_distribution->getQuery([ "order_goods_id" => $order_goods_id ]);
				#得到当前订单的利润
				$goods_return = $order_goods["goods_return"];
				#商品的买价
				$goods_money = $order_goods["real_pay"];
				if (!empty($commission_list) && count($commission_list) > 0) {
					foreach ($commission_list as $k => $commission_obj) {
						$id = $commission_obj["id"];
						$commission_rate = $order_goods['commission_rate_promoter'];
						$commission_money = $goods_return * $commission_rate / 100;
						$commossion_distribution->update([ "goods_money" => $goods_money, "goods_return" => $goods_return, "commission_money" => $commission_money ], [ "id" => $id ]);
					}
				}
			}
			$commossion_distribution->commit();
			return 1;
		} catch (\Exception $e) {
			$commossion_distribution->rollback();
			return $e->getMessage();
		}
	}
	
	/**
	 * 添加佣金分配信息
	 * @param unknown $shop_id
	 * @param unknown $promoter_id 分销商ID
	 * @param unknown $order_id 订单ID
	 * @param unknown $order_goods_id 订单商品ID
	 * @param unknown $goods_money 商品实际卖价
	 * @param unknown $goods_cost
	 * @param unknown $goods_return
	 * @param unknown $promoter_level
	 * @param unknown $goods_commission_rate
	 * @param unknown $commission_rate
	 */
	private function addOrderDistributionCommission($shop_id, $promoter_id, $order_id, $order_goods_id, $goods_money, $goods_cost, $goods_return, $promoter_level, $commission_rate)
	{
		$commossion_distribution = new NfxCommissionDistributionModel();
		if ($goods_return <= 0) return 1;
		
		$data = array(
			'serial_no' => getSerialNo(),
			'shop_id' => $shop_id,
			'promoter_id' => $promoter_id,
			'promoter_level' => $promoter_level,
			'order_id' => $order_id,
			'order_goods_id' => $order_goods_id,
			'goods_money' => $goods_money,
			'goods_cost' => $goods_cost,
			'goods_return' => $goods_return,
			'goods_commission_rate' => $commission_rate,
			'commission_rate' => $commission_rate,
			'commission_money' => $goods_return * $commission_rate / 100,
			'create_time' => time()
		);
		$commossion_distribution->save($data);

		return $commossion_distribution->id;
	}
	
	/**
	 * 股东分红计算
	 */
	public function orderPartnerCommission()
	{
		if ($this->is_partner_enable == 1) {
			
			$commission_partner = new NfxCommissionPartnerModel();
			if (empty($this->order_info)) {
				return 1;
			}
			$commission_partner->startTrans();
			try {
				foreach ($this->order_info['order_goods_list'] as $k => $order_goods) {
					if (empty($order_goods['commission_rate'])) {
						continue;
					}
					//获取佣金信息
					$commission_rate = $order_goods['commission_rate'];
					if (!empty($commission_rate)) {
						if ($commission_rate['is_open'])    //启动分销
						{
							//查询对应分销商
							$partner_id = $this->partner_id;
							if ($partner_id != 0) {
								
								$partner = new NfxPartner();
								$parents_array = $partner->getPartnerParents($partner_id);
								$partner_commission_rate = 0;
								foreach ($parents_array as $k => $parent_partner) {
									$partner_level_model = new NfxPartnerLevelModel();
									$partner_level_info = $partner_level_model->get($parent_partner['partner_level']);
									if ($partner_level_info['commission_rate'] > $partner_commission_rate) {
										$real_commission_rate = $partner_level_info['commission_rate'] - $partner_commission_rate;
										$partner_commission_rate = $partner_level_info['commission_rate'];
										$this->addOrderPartnerCommission($this->instance_id, $parent_partner['partner_id'], $parent_partner['partner_level'], $partner_id, $this->order_info['order_id'], $order_goods['order_goods_id'], $order_goods['real_pay'], $order_goods['cost_price'], $order_goods['goods_return'], $commission_rate['partner_commission_rate'], $real_commission_rate);
										
									}
								}
							}
							
						}
					}
				}
				$commission_partner->commit();
				return 1;
			} catch (\Exception $e) {
				$commission_partner->rollback();
				return $e->getMessage();
			}
		} else {
			return 1;
		}
	}
	
	/**
	 * 重新计算订单的订单的股东分红
	 */
	public function updateOrderPartnerCommission()
	{
		$commission_partner = new NfxCommissionPartnerModel();
		if (empty($this->order_info)) {
			return 1;
		}
		$commission_partner->startTrans();
		try {
			foreach ($this->order_info['order_goods_list'] as $k => $order_goods) {
				#订单项id
				$order_goods_id = $order_goods["order_goods_id"];
				#查询当前订单项产生的股东佣金流水
				$commission_list = $commission_partner->getQuery([ "order_goods_id" => $order_goods_id ]);
				#得到当前订单的利润
				$goods_return = $order_goods["goods_return"];
				#商品的买价
				$goods_money = $order_goods["real_pay"];
				if (!empty($commission_list) && count($commission_list) > 0) {
					foreach ($commission_list as $k => $commission_obj) {
						$id = $commission_obj["id"];
						$goods_commission_rate = $commission_obj["goods_commission_rate"];
						$commission_rate = $commission_obj["commission_rate"];
						$commission_money = $goods_return * $goods_commission_rate / 100 * $commission_rate / 100;
						$commission_partner->update([ "goods_money" => $goods_money,
							"goods_return" => $goods_return, "commission_money" => $commission_money ], [ "id" => $id ]);
					}
				}
			}
			$commission_partner->commit();
			return 1;
		} catch (\Exception $e) {
			$commission_partner->rollback();
			return $e->getMessage();
		}
	}
	
	/**
	 * 添加股东分红
	 */
	private function addOrderPartnerCommission($shop_id, $partner_id, $partner_level, $order_partner_id, $order_id, $order_goods_id, $goods_money, $goods_cost, $goods_return, $goods_commission_rate, $commission_rate)
	{
		
		$commission_partner = new NfxCommissionPartnerModel();
		if ($goods_return < 0) {
			$goods_return = 0;
		}
		$data = array(
			'serial_no' => getSerialNo(),
			'shop_id' => $shop_id,
			'partner_id' => $partner_id,
			'partner_level' => $partner_level,
			'order_partner_id' => $order_partner_id,
			'order_id' => $order_id,
			'order_goods_id' => $order_goods_id,
			'goods_money' => $goods_money,
			'goods_cost' => $goods_cost,
			'goods_return' => $goods_return,
			'goods_commission_rate' => $goods_commission_rate,
			'commission_rate' => $commission_rate,
			'commission_money' => $goods_return * $goods_commission_rate / 100 * $commission_rate / 100,
			'create_time' => time()
		);
		$commission_partner->save($data);
		return $commission_partner->id;
		
	}
	
	/* 区域分销分红
	 */
	public function orderRegionAgentCommissionNew()
	{
		$region_agent_model = new NfxCommissionRegionAgentModel();
		if (empty($this->order_info)) {
			return 1;
		}
		
		$receiver_province = $this->order_info["receiver_province"];
		$receiver_city = $this->order_info["receiver_city"];
		$receiver_district = $this->order_info["receiver_district"];
		$promote_region_agent_model = new NfxPromoterRegionAgentModel();
		#查询当前县的代理人
		$condition["agent_type"] = 1;
		$condition["agent_provinceid"] = $receiver_province;
		$condition["is_audit"] = 1;
		$province_region = $promote_region_agent_model->getInfo($condition, "*");
		#查询当前市的代理人
		$condition_city["agent_type"] = 2;
		$condition_city["agent_cityid"] = $receiver_city;
		$condition_city["is_audit"] = 1;
		$city_region = $promote_region_agent_model->getInfo($condition_city, "*");
		#查询当前区县的代理人
		$condition_district["agent_type"] = 3;
		$condition_district["agent_districtid"] = $receiver_district;
		$condition_district["is_audit"] = 1;
		$district_region = $promote_region_agent_model->getInfo($condition_district, "*");
		#查询当前店铺的区域分销的分红比率
		$shop_region_agent_model = new NfxShopRegionAgentConfigModel();
		$condition_config["shop_id"] = $this->instance_id;
		$region_agent_config = $shop_region_agent_model->getInfo($condition_config, "*");
		if (!empty($region_agent_config)) {
			$province_rate = $region_agent_config["province_rate"];
			$city_rate = $region_agent_config["city_rate"];
			$district_rate = $region_agent_config["district_rate"];
			$region_agent_model->startTrans();
			try {
				foreach ($this->order_info['order_goods_list'] as $k => $order_goods) {
					if (empty($order_goods['commission_rate'])) {
						continue;
					}
					//获取佣金信息
					$commission_rate = $order_goods['commission_rate'];
					if (!empty($commission_rate)) {
						if ($commission_rate['is_open'])    //启动分销
						{
							#当前订单项的利润
							$goods_return = $order_goods["goods_return"];
							#当前商品所拿出的区域分销比率
							$region_rate = $commission_rate["regionagent_commission_rate"];
							#计算区域分销的金额
							$goods_return = $goods_return * $region_rate / 100;
							#该省具有代理商
							if (!empty($province_region)) {
								
								$province_commission = $goods_return * $province_rate / 100;
								$this->addOrderRegionAgentCommission($this->instance_id, $province_region["region_agent_id"],
									$province_region["uid"], $province_region["promoter_id"], $order_goods["order_id"],
									$order_goods["order_goods_id"], $order_goods["real_pay"], $order_goods["cost_price"],
									$order_goods["goods_return"], 1, $province_rate, $province_commission, $region_rate);
							}
							#该市具有代理商
							if (!empty($city_region)) {
								$city_commission = $goods_return * $city_rate / 100;
								$this->addOrderRegionAgentCommission($this->instance_id, $city_region["region_agent_id"],
									$city_region["uid"], $city_region["promoter_id"], $order_goods["order_id"],
									$order_goods["order_goods_id"], $order_goods["real_pay"], $order_goods["cost_price"],
									$order_goods["goods_return"], 2, $city_rate, $city_commission, $region_rate);
							}
							#该区县具体有代理商
							if (!empty($district_region)) {
								$district_commission = $goods_return * $district_rate / 100;
								$this->addOrderRegionAgentCommission($this->instance_id, $district_region["region_agent_id"],
									$district_region["uid"], $district_region["promoter_id"], $order_goods["order_id"],
									$order_goods["order_goods_id"], $order_goods["real_pay"], $order_goods["cost_price"],
									$order_goods["goods_return"], 3, $district_rate, $district_commission, $region_rate);
							}
						}
					}
				}
				$region_agent_model->commit();
				return 1;
			} catch (\Exception $e) {
				$region_agent_model->rollback();
				return $e->getMessage();
			}
		} else {
			return 1;
		}
	}

    /* 区域分销分红
     */
    public function orderRegionAgentCommission()
    {
        if (empty($this->order_info)) {
            return 1;
        }

        //如果是用赠送余额支付的，则没有服务奖励
        if($this->order_info['payment_type'] == 13 || $this->order_info['region_agent_uid'] != 0) return 1;

        //查询与收获地址相同的服务中心
        //查询的结果可能是自己的邀请人 也可能不是
        $receiver_province = $this->order_info["receiver_province"];
        $receiver_city = $this->order_info["receiver_city"];
        $receiver_district = $this->order_info["receiver_district"];
        $promote_region_agent_apply_model = new NfxPromoterRegionAgentApplyModel();
        $promote_region_agent_apply_info = $promote_region_agent_apply_model->getInfo([
            'province_id' => $receiver_province,
            'city_id' => $receiver_city,
            'district_id' => $receiver_district,
            'audit_status' => 'confirm_pass',
        ]);
        if(empty($promote_region_agent_apply_info)) return 1;

        //服务中心信息
        $region_agent_promoter_id = $promote_region_agent_apply_info['promoter_id'];
        $region_agent_uid = $promote_region_agent_apply_info['uid'];

        //获取服务中心品类
        $apply_model = new NfxPromoterRegionAgentApplyModel();
        $apply_list = $apply_model->getQuery(['uid' => $region_agent_uid, 'audit_status' => 'confirm_pass'], 'category_ids', 'apply_id asc');
        $category_ids_arr = [];
        foreach($apply_list as $key=>$val){
            $category_ids_arr[] = $val['category_ids'];
        }
        $category_ids = join(',', $category_ids_arr);
        $category_id_arr = explode(',', $category_ids);
        
        $region_agent_model = new NfxCommissionRegionAgentModel();
        $goods_model = new NsGoodsModel();
        $region_agent_model->startTrans();
        try {
            foreach ($this->order_info['order_goods_list'] as $k => $order_goods) {
                //品类判断，品类不一致，无服务奖励
                $goods_info = $goods_model->getInfo(['goods_id' => $order_goods['goods_id']], 'category_id');
                if(!in_array($goods_info['category_id'], $category_id_arr)){
                    continue;
                }

                #当前订单项的利润
                $goods_return = $order_goods["goods_return"];
                #当前商品所拿出的区域分销比率
                $region_rate = $this->reward_set['value']['agent_reward_rate'];
                #计算区域分销的金额
                $agent_commission = $goods_return * $region_rate / 100;
                $this->addOrderRegionAgentCommission(
                        $this->instance_id,
                        $region_agent_promoter_id,
                        $region_agent_uid,
                        $region_agent_promoter_id,
                        $order_goods["order_id"],
                        $order_goods["order_goods_id"],
                        $order_goods["real_pay"],
                        $order_goods["cost_price"],
                        $order_goods["goods_return"],
                        3,
                        $region_rate,
                        $agent_commission,
                        $region_rate
                );
            }
            $region_agent_model->commit();
            return 1;
        } catch (\Exception $e) {
            $region_agent_model->rollback();
            return $e->getMessage();
        }
    }
	
	/**
	 * 重新计算订单的区域分销分红
	 */
	public function updateOrderRegionAgentCommission()
	{
		$region_agent_model = new NfxCommissionRegionAgentModel();
		if (empty($this->order_info)) {
			return 1;
		}
		$region_agent_model->startTrans();
		try {
			foreach ($this->order_info['order_goods_list'] as $k => $order_goods) {
				#订单项id
				$order_goods_id = $order_goods["order_goods_id"];
				#查询当前订单项产生的区域分销佣金流水
				$commission_list = $region_agent_model->getQuery([ "order_goods_id" => $order_goods_id ]);
				#得到当前订单的利润
				$goods_return = $order_goods["goods_return"];
				#商品的买价
				$goods_money = $order_goods["real_pay"];
				if (!empty($commission_list) && count($commission_list) > 0) {
					foreach ($commission_list as $k => $commission_obj) {
						$id = $commission_obj["id"];
						$agent_rate = $this->reward_set['value']['agent_reward_rate'];
						$commission_money = $goods_return * $agent_rate / 100;
						$region_agent_model->update([ "goods_money" => $goods_money,
							"goods_return" => $goods_return, "commission" => $commission_money ], [ "id" => $id ]);
					}
				}
			}
			$region_agent_model->commit();
			return 1;
		} catch (\Exception $e) {
			$region_agent_model->rollback();
			return $e->getMessage();
		}
		
	}
	
	/**
	 * 区域分销分红记录添加
	 */
	private function addOrderRegionAgentCommission($shop_id, $region_agent_id, $uid, $promoter_id, $order_id, $order_goods_id, $goods_money, $goods_cost, $goods_return, $commission_type, $commission_rate, $commission, $goods_commission_rate)
	{
		$region_agent_model = new NfxCommissionRegionAgentModel();
		$data = array(
			"shop_id" => $shop_id,
			"region_agent_id" => $region_agent_id,
			"uid" => $uid,
			"serial_no" => getSerialNo(),
			"promoter_id" => $promoter_id,
			"order_id" => $order_id,
			"order_goods_id" => $order_goods_id,
			"goods_money" => $goods_money,
			"goods_cost" => $goods_cost,
			"goods_return" => $goods_return,
			"commission_type" => $commission_type,
			"commission_rate" => $commission_rate,
			"commission" => $commission,
			"goods_commission_rate" => $goods_commission_rate,
            "create_time" => time(),
		);
		$region_agent_model->save($data);
		return $region_agent_model->id;
	}

    /**
     * 处理推广商品数据
     *
     */
    public function dealWithPromoterGoods()
    {
        if(empty($this->order_info)) return 1;

        $promoter_goods_model = new NfxPromoterGoodsModel();

        $commission_distribution_model = new NfxCommissionDistributionModel();

        $promoter_goods_model->startTrans();
        try{
            $promoter_goods_data = [];
            foreach($this->order_info['order_goods_list'] as $key=>$val){

                // 添加商品推广记录
                $goods_id = $val['goods_id'];
                $promoter_id = $this->promoter_id;
                $uid = $this->promoter_uid;
                $promoter_goods_info = $promoter_goods_model->getInfo(['promoter_id' => $promoter_id, 'goods_id' => $goods_id]);
                if(empty($promoter_goods_info)){
                    //获取红旗手购买该产品的父级推广人
                    $commission_distribution_info = $commission_distribution_model->getInfo(['order_goods_id' => $val['order_goods_id']]);
                    if(!empty($commission_distribution_info)){
                        $parent_promoter = $commission_distribution_info['promoter_id'];
                    }else{
                        $parent_promoter = 0;
                    }

                    $promoter_goods_data[] = [
                        'promoter_id' => $promoter_id,
                        'uid' => $uid,
                        'goods_id' => $goods_id,
                        'level' => 'middle',
                        //确认状态 每月8日进行确认
                        'confirm_status' => 0,
                        'create_time' => time(),
                        //红旗手购买该产品的父级推广人
                        'parent_promoter' => $parent_promoter,
                    ];
                }
            }

            $res = null;
            if(!empty($promoter_goods_data)){
                $res = $promoter_goods_model->saveAll($promoter_goods_data);
            }
            $promoter_goods_model->commit();

            return $res;
        }catch(\Exception $e){
            $promoter_goods_model->rollback();
            return $e->getMessage();
        }
    }
}